package com.tianluo.tianluobookstore.service.impl;

import com.tianluo.tianluobookstore.domain.view.BookPageVO;
import com.tianluo.tianluobookstore.domain.view.HomePageVO;
import com.tianluo.tianluobookstore.domain.view.UserInfoVO;
import com.tianluo.tianluobookstore.enums.CommonCodeEnum;
import com.tianluo.tianluobookstore.exception.BizException;
import com.tianluo.tianluobookstore.request.QueryBookRequest;
import com.tianluo.tianluobookstore.service.BookService;
import com.tianluo.tianluobookstore.service.BookStoreService;
import com.tianluo.tianluobookstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

@Service
public class BookStoreServiceImpl implements BookStoreService {

    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;
    @Override
    public HomePageVO homePage(String phoneNumber) {

        QueryBookRequest queryBookRequest = QueryBookRequest.builder().pageNum(1).pageSize(10).build();
        ExecutorService tianLuoExecutor = buildExecutor();
        CompletableFuture<BookPageVO> bookFuture
                =CompletableFuture.supplyAsync(() -> bookService.pageQueryBookList(queryBookRequest),tianLuoExecutor);
        CompletableFuture<UserInfoVO> userFuture
                =CompletableFuture.supplyAsync(() -> userService.selectByPhone(phoneNumber),tianLuoExecutor);

        try {
            // 2. 等待并组合结果（最长等待3秒）
            BookPageVO books = bookFuture.get(10, TimeUnit.SECONDS);
            UserInfoVO user = userFuture.get(10, TimeUnit.SECONDS);

            HomePageVO homePageVO = new HomePageVO();
            homePageVO.setBookPageVO(books);
            homePageVO.setUserInfoVO(user);

            // 3. 返回组合结果
            return homePageVO;

        } catch (TimeoutException e) {
            throw new BizException(CommonCodeEnum.TRY_LATER);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    private ExecutorService buildExecutor() {
        int corePoolSize = 10;     // 核心线程数
        int maxPoolSize = 10;      // 最大线程数（固定大小）
        long keepAliveTime = 0L;   // 非核心线程空闲存活时间（固定线程池可设为0）
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 有界队列（容量100）
        RejectedExecutionHandler rejectionHandler = new ThreadPoolExecutor.AbortPolicy(); // 拒绝策略

        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                workQueue,
                rejectionHandler
        );
    }
}
